from django.utils.translation import gettext_lazy, gettext as _
from rest_framework.permissions import IsAuthenticated
from rest_framework.serializers import Serializer
from rest_framework.response import Response
from rest_framework.decorators import action
from drf_yasg.utils import swagger_auto_schema

from core import errors
from utils.paginators import NoPaginatorInspector
from apps.api.paginations import NewPageNumberPagination100
from apps.api.viewsets import NormalGenericViewSet, serializer_error_msg
from apps.app_tx_meeting import serializers
from apps.app_tx_meeting.models import MeetingRoom
from apps.app_tx_meeting.managers import MeetingUserWrapper


class MeetingRoomConfigViewSet(NormalGenericViewSet):
    permission_classes = [IsAuthenticated]
    pagination_class = NewPageNumberPagination100
    lookup_field = 'id'

    @swagger_auto_schema(
        tags=['tx_meeting'],
        operation_summary=gettext_lazy('会议室资源配置查询'),
        paginator_inspectors=[NoPaginatorInspector],
        responses={
            200: ''''''
        }
    )
    def list(self, request, *args, **kwargs):
        """
        会议室资源配置查询

            http code 200:
            {
                "room_info": {
                {
                    "id": "main",
                    "creation_time": "2025-04-24T02:27:24.960830Z",
                    "update_time": "2025-05-21T02:20:25.499773Z",
                    "type_50_num": 20，    # 类型为50方会议室数量
                    "type_50_visible": true,    # 会议室可见性，true(可见)，false(不可见)
                    "type_100_num": 10，    # 类型为100方会议室数量
                    "type_100_visible": true,    # 会议室可见性，true(可见)，false(不可见)
                    "type_300_num": 6，    # 类型为300方会议室数量
                    "type_300_visible": true,    # 会议室可见性，true(可见)，false(不可见)
                    "type_500_num": 2，    # 类型为500方会议室数量
                    "type_500_visible": false,    # 会议室可见性，true(可见)，false(不可见)
                    "type_1000_num": 0，    # 类型为1000方会议室数量
                    "type_1000_visible": false,    # 会议室可见性，true(可见)，false(不可见)
                }
            }
        """
        obj = MeetingRoom.get_main_instance()
        slzer = self.get_serializer(obj)
        return Response(data={
            'room_info': slzer.data
        })

    @swagger_auto_schema(
        tags=['tx_meeting'],
        operation_summary=gettext_lazy('修改会议室资源配置'),
        paginator_inspectors=[NoPaginatorInspector],
        responses={
            200: ''''''
        }
    )
    @action(methods=['POST'], detail=False, url_path='update', url_name='update')
    def update_room_config(self, request, *args, **kwargs):
        """
        修改会议室资源配置，需要管理员权限

            http code 200:
            {
                "room_info": {
                    "type_50_num": 20，    # 类型为50方会议室数量
                    "type_100_num": 10，    # 类型为100方会议室数量
                    "type_300_num": 6，    # 类型为300方会议室数量
                    "type_500_num": 2，    # 类型为500方会议室数量
                    "type_1000_num": 0，    # 类型为1000方会议室数量
                }
            }
        """
        serializer = self.get_serializer(data=request.data)
        if not serializer.is_valid(raise_exception=False):
            msg = serializer_error_msg(serializer.errors)
            return self.exception_response(exc=errors.InvalidArgument(message=msg))

        ur_wrapper = MeetingUserWrapper(user=request.user)
        if not ur_wrapper.is_active_user():
            return self.exception_response(
                errors.AccessDenied(message=_('你的账号状态无效')))

        if not ur_wrapper.is_admin():
            return self.exception_response(
                errors.AccessDenied(message=_('你没有管理员权限')))

        obj = MeetingRoom.get_main_instance()
        data = serializer.validated_data
        obj.type_50_num = data['type_50_num']
        obj.type_100_num = data['type_100_num']
        obj.type_300_num = data['type_300_num']
        obj.type_500_num = data['type_500_num']
        obj.type_1000_num = data['type_1000_num']

        if data['type_50_visible'] is not None:
            obj.type_50_visible = data['type_50_visible']

        if data['type_100_visible'] is not None:
            obj.type_100_visible = data['type_100_visible']

        if data['type_300_visible'] is not None:
            obj.type_300_visible = data['type_300_visible']

        if data['type_500_visible'] is not None:
            obj.type_500_visible = data['type_500_visible']

        if data['type_1000_visible'] is not None:
            obj.type_1000_visible = data['type_1000_visible']

        obj.save(force_update=True)

        return Response(data={
            'room_info': serializers.MeetingRoomConfigSerializer(obj).data
        })

    def get_serializer_class(self):
        if self.action in ['list', 'update_room_config']:
            return serializers.MeetingRoomConfigSerializer

        return Serializer
